<META HTTP-EQUIV="pragma" CONTENT="no-cache">
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>用户</title>
  <link rel="stylesheet" href="../../../layui/css/layui.css">
  <link rel="stylesheet"  href="../../../css/zTreeStyle/zTreeStyle.css">
  <script src="../../../layui/layui.js"></script>
  <script type="text/javascript" src="../../../js/jquery-1.4.4.min.js"></script>
  <script type="text/javascript" src="../../../js/jquery.ztree.core.js"></script>
  <script type="text/javascript" src="../../../js/jquery.ztree.excheck.js"></script>
  <script type="text/javascript" src="../../../js/jquery.ztree.exedit.js"></script>
</head>
<style type="text/css">
  body{
    height: 100%;
    width: 100%;
    margin-top: 11px;
  }

  .border{
    border:1px solid blue;
    margin-left: 11px;
  }
</style>

<body >
<!-- 内容主体区域 -->
<div class="layui-row layui-col-space5">
  <div class="layui-col-md5 border">
    <div class="layui-fluid layui-form">
      <div class="layui-form-item">
        <div class="layui-input-inline " style=" width: 638px;">
          <button class="layui-btn layui-btn-primary addRole">新增</button>
          <button class="layui-btn updateRole">修改</button>
          <button class="layui-btn layui-btn-normal deleteRole">删除</button>
          <!--      <button class="layui-btn">默认按钮</button>
                <button class="layui-btn layui-btn-normal">百搭按钮</button>-->
        </div>

      </div>
    </div>

    <div id="pTable" >
      <table id="layui_table_id" class="layui-table" lay-skin="line" lay-filter="test" style="width: 1680px">

      </table>
      <!--<div id="laypage"></div>-->
    </div>
  </div>
  <div class="layui-col-md5 border">
    <div class="layui-fluid layui-form">
      <div class="layui-form-item">
        <div class="layui-input-inline " style=" width: 638px;">
          <button class="layui-btn layui-btn-primary updateRolePower">更新权限</button>
          <!--      <button class="layui-btn">默认按钮</button>
                <button class="layui-btn layui-btn-normal">百搭按钮</button>-->
        </div>

      </div>
    </div>
    <div id="treeDiv" >
      <div class="layui-form-item ">
        <div class="layui-inline">
          <div class="tree tree-selectable"><ul id="tree" class="ztree"></ul></div>
        </div>
      </div>
    </div>
    </div>
  </div>
</div>
<input name="listMenuId" id="listMenuId"  type="hidden" value="" class="layui-input">

</body>
</html>

<script type="text/javascript">
  layui.use(['form','laydate','layer','table','laypage','util'],function(){
    var form = layui.form;
    var laydate=layui.laydate;
    var $ = layui.$;
    productsearch(1);
    rymeu();
    function productsearch(page) {

      var table = layui.table,
      laydate = layui.laydate,
      laypage = layui.laypage;
      var form = layui.form;
      table.render({
        elem : '#layui_table_id',
        url : '/admin/systemRoles/getAll.handler',
        cols : [ [
              {checkbox: true,
                filter:'test'
              }
              ,
              {
                field : 'roleName',
                title : '角色名称',
                sort : true,
                align : 'center'
              }
              , {
                field : 'roleCode',
                title : '角色编号',
                align : 'center'
              }



        ] ],
        page : true,
        where : {
          filterExpr:"online=0",
        },
        responseHandler: function (res, curr,count) {
          $('#pageNum').val(curr);
          console.log(res)
          return {
            "count": res.length,
            "data": res,
            "code": 0,//code值为200表示成功
            "msg": ""
          }
        },
        done : function(res, curr, count) {
          console.log(res)
          $('#pageNum').val(curr);

        }
      })
      table.on('checkbox(test)', function(obj){
        console.log(layui.table.checkStatus('layui_table_id').data);
        var data =layui.table.checkStatus('layui_table_id').data ;
        if(data.length>0){
            updateNode(data[0].recordId);
        }
      });
     // 监听工具条
      table.on('tool(test)', function(obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data, //获得当前行数据
                layEvent = obj.event; //获得 lay-event 对应的值
        if (layEvent == 'detail') {u
          queryById(data.id);
        } else if (layEvent == 'del') {
          //alert(data.id)
          var pageNum = $('#pageNum').val();
          layer.confirm('真的删除行么', function(index){
            deleteById(data.id);
            layer.close(index);
            //向服务端发送删除指令
          });
        } else if (layEvent === 'edit') {
          layer.msg('编辑操作');
        }
      });
      //常规用法
      laydate.render({
        elem : '#createDate'
      });
      //常规用法
      laydate.render({
        elem : '#processingTime'
      });

    }
    $(".tingzhi").on("click",function(){
      var data = layui.table.checkStatus('layui_table_id').data;
      if(data.length>1||data.length<1){
        alert("请选中一条数据");
        return false;
      }
      $.ajax({
        type:'POST',
        url:'/admin/systemUsers/disableUser.handler',
        data: {userId:data[0].recordId},
        success: function(data){
          alert("操作成功！");
          productsearch(1);
        },
        error:function(data){
          alert("操作失败");
          console.log(data);
        }
      })
    })


    $(".qidong").on("click",function(){
      var data = layui.table.checkStatus('layui_table_id').data;
      if(data.length>1||data.length<1){
        alert("请选中一条数据");
        return false;
      }
      $.ajax({
        type:'POST',
        url:'/admin/systemUsers/enableUser.handler',
        data: {userId:data[0].recordId},
        success: function(data){
          alert("操作成功！");
          productsearch(1);
        },
        error:function(data){
          alert("操作失败");
          console.log(data);
        }
      })
    })
      $(".shouquan").on("click",function(){
          var data = layui.table.checkStatus('layui_table_id').data;
          if(data.length<1){
              alert("请选中一条数据");
              return false;
          }
          layer.open({
              type:2,
              area:[482+'px',315+'px'],
              fix:false,
              offset: '80px',
              maxmin:true,
              shadeClose:true,
              scrollbar: false,
              shade:0.4,
              title:'授权',
              content:['authorize.html'],
              success:function(layero,index){
                  var iframe = window['layui-layer-iframe' + index];
                  // 向子页面的全局函数child传参
                  iframe.child(data[0]);
                  console.log("成功");
              },
              fail:function(data){
                  console.log(data);
              }
          })
      })


    $(".deleteRole").on("click",function(){
      var data = layui.table.checkStatus('layui_table_id').data;
      if(data.length<1){
        alert("请选中一条数据");
        return false;
      }
      layer.confirm('确定删除该角色？', function(index){
        var deleteList = [];
        for(var i=0 ;i<data.length;i++){
          var id = data[i].recordId;
          var temp =id+"";
          deleteList.push(temp);
        }
        console.log(deleteList);
        $.ajax({
          type:'POST',
          url:'/admin/systemRoles/delete.handler',
          //data: JSON.stringify(deleteList),
          data: JSON.stringify(deleteList),
          contentType: "application/json",
          success: function(data){
            layer.close(index);
            alert("操作成功！");
            productsearch(1);
          },
          error:function(data){
            alert("操作失败");
            console.log(data);
          }
        })
        //向服务端发送删除指令
      });



    })

    $(".addRole").on("click",function(){
      layer.open({
        type:2,
        area:[482+'px',315+'px'],
        fix:false,
        offset: '80px',
        maxmin:true,
        shadeClose:true,
        scrollbar: false,
        shade:0.4,
        title:'新增角色',
        content:['eidt_role.html'],
        success:function(layero,index){
          console.log("成功");
        },
        fail:function(data){
          console.log(data);
        }
      })
    })
    $(".updateRole").on("click",function(){
      console.log(layui.table.checkStatus('layui_table_id'));
      var data = layui.table.checkStatus('layui_table_id').data;
      if(data.length>1){
        alert("请选中一条数据");
        return false;
      }
      layer.open({
        type:2,
        area:[482+'px',315+'px'],
        fix:false,
        offset: '80px',
        maxmin:true,
        shadeClose:true,
        scrollbar: false,
        shade:0.4,
        title:'修改角色',
        content:['eidt_role.html'],
        success:function(layero,index){
          // 获取子页面的iframe
          var iframe = window['layui-layer-iframe' + index];
          // 向子页面的全局函数child传参
          iframe.child(data[0]);
          console.log("成功");
        },
        fail:function(data){
          console.log(data);
        }
      })
    })
    $(".updateRolePower").on("click",function(){

      updateRole();
    })
  });
  function userStatus(t){
     if(t==0){
       return '启用';
     }else{
       return '禁用';
     }
    return util.toDateString(t1);
  }

  var setting = {
    check:{
      enable:true
    },
    data:    {
      simpleData:{
        enable:true
      }
    },
    callback:{
      onCheck:onCheck// 点击属性菜单复选框回调函数
    }

  };
  function onCheck(e,treeId,treeNode){
    var treeObj1=$.fn.zTree.getZTreeObj("tree"),// 参数为目标ul的id
            nodes1=treeObj1.getCheckedNodes(true),//  获取选中的节点集合
            v1="";
    // 将选中的系统菜单加载到右边
    var target_table1 = $(".systemTable");//要加载的table的位置
    //下面的for循环根据自己需要修改
    for(var i=0;i<nodes1.length;i++){
      // 一级菜单加粗
      if (nodes1[i].getParentNode() == null) {
        v1+= '<tr><td class="rightTd" id="'+nodes1[i].id+'"><b>'+nodes1[i].name+'</b></td></tr>';
      } else {
        v1+= '<tr><td class="rightTd" id="'+nodes1[i].id+'">'+nodes1[i].name+'</td></tr>';
      }
    }
    //显示在table中
    target_table1.html(v1);
  }


  function updateRole() {
      var data = layui.table.checkStatus('layui_table_id').data;
      var roleid = 0
      if(data.length==1){
        roleid =  data[0].recordId;
        //return false;
      }

      if(roleid==0){
        alert('请选择一条记录');
      }
      $.fn.zTree.getZTreeObj("tree");
      var treeObj=$.fn.zTree.getZTreeObj("tree");
      var nodes=treeObj.getCheckedNodes(true);
      var tempList = [];
      for(var i=0;i<nodes.length;i++) {
        var temp = {};
        if(nodes[i].privilegeCode==null){
          temp.privilegeCode = 'RUN';
          temp.programId = nodes[i].programId;
        }else{
          temp.privilegeCode = nodes[i].privilegeCode;
          temp.programId = nodes[i].programId;
          temp.recordId = nodes[i].recordId;
        }
        tempList.push(temp);
      }
      console.log(tempList);
      $.ajax({
        type:'POST',
        url:'/admin/systemRoles/updateRolePrivileges.handler?roleId='+roleid,
        data: JSON.stringify(tempList),
        contentType: "application/json",
        success: function(data){
          alert("操作成功！");
          // window.parent.location.reload(); //刷新父页面
          // var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
          // parent.layer.close(index);  // 关闭layer
        },
        error:function(data){
          alert("操作失败");
          console.log(data);
        }
      })
  }

  function updateNode(roleid,result){
    //removeChildNodesTree();
    var t = $("#tree");
    if(result!=undefined){
      t = $.fn.zTree.init(t, setting, result);
    }else{
      removeChildNodesTree();
    }

    var zTree = $.fn.zTree.getZTreeObj("tree");
    var  node=zTree.getNodeByParam("recordId",'SYS01');
    console.log(node);
    $.ajax({
      type:'get',
      url:'/admin/systemRoles/getRolePrivileges.handler?roleId='+roleid,
      dataType:"json",
      async:false,
      success:function (res) {
        console.log(res);
        var jsonList = res;
        var listMenuId = [];
        $(jsonList).each(function (i) {
          var meu=jsonList[i];
          listMenuId.push(meu.recordId);
          var  node=zTree.getNodeByParam("recordId",meu.programPrivilegeId);
          var  node2=zTree.getNodeByParam("recordId",meu.programId);
          if(node!=null){
            zTree.checkNode(node, true, false);
            zTree.updateNode(node);
            var parent = node.getParentNode();
            if(!parent.open){
              zTree.expandNode(parent,true,true);
            }
          }
          if(node2!=null){
            zTree.checkNode(node2, true, false);
            zTree.updateNode(node2);
          }
        })
        $('#listMenuId').val(listMenuId);
      }
    })

  }
  function rymeu(roleid){
    $.ajax({
      type:'get',
      url: '/admin/systemRoles/getAllMenuWithPrivilege.handler?node=root',
      dataType:'json',
      async:false,
      success:function (res){
        var result=res;
        console.log(result);
        //if (result.length>1) {
        for(var i= 0 ;i<result.length;i++){
          var temp =  result[i];
          temp.recordId = temp.programId;
          var chider = temp.children;
          for(var j=0;j<chider.length;j++){
            var temp2= chider[j];
            temp2.recordId = temp2.programId;
          }
        }

        updateNode(null,result);


        }

    //  }
    })
  }
  function removeChildNodesTree()
  {
    var zTree = $.fn.zTree.getZTreeObj("tree");
    //获取全部节点数据
    var nodes =zTree.getCheckedNodes(true);
    for (var i=0, l=nodes.length; i < l; i++)
    {
      zTree.checkNode(nodes[i], false, true);
      //清空选中的第一个节点的子节点
    }
  }
</script>


<script type="text/html" id="userStatus">


        {{ userStatus(d.userStatus) }}
</script>